import { Button, message } from 'antd';
import { useRef } from 'react';

/**
 * https://developer.mozilla.org/zh-CN/docs/Web/API/MediaDevices/getUserMedia
*/
const CanvasSnap = () => {
    const videoRef = useRef<HTMLVideoElement>(null)
    const canvasRef = useRef<HTMLCanvasElement>(null);

    const handleErr = (e?: Error) => {
        message.error(e?.message || `摄像头打开失败`);
    }

    const openCamera = async () => {
        try {
            /**
             * 提示用户给予使用媒体输入的许可，成功后会产生一个 MediaStream，
             * 里面包含了请求的媒体类型的轨道
            */
            const stream = await navigator.mediaDevices.getUserMedia({
                video: true,    // 只需要视频轨道
                audio: false,
            });
            const video = videoRef.current as HTMLVideoElement;
            /** 获取所有的视频轨道信息 */
            const videoTracks = stream.getVideoTracks();
            console.log('使用的设备是: ', videoTracks[0].label);
            video.srcObject = stream;
        } catch (e) {
            console.log('getUserMedia err: ', e);
            handleErr(e as Error);
        }
    }

    const getSnap = () => {
        const video = videoRef.current as HTMLVideoElement;
        const canvas = canvasRef.current as HTMLCanvasElement;
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        const ctx = canvas.getContext('2d');
        // drawImage 第一参数：HTMLOrSVGImageElement | HTMLVideoElement | HTMLCanvasElement | ImageBitmap | OffscreenCanvas;
        ctx?.drawImage(video, 0, 0, canvas.width, canvas.height);
    }

    return (
        <div>
            <h3>用 canvas 截取视频某一帧</h3>
            <div style={{
                display: 'flex',
                alignItems: 'flex-start',
                gap: 100
            }}>
                <div>
                    <Button onClick={openCamera} type="primary">打开摄像头</Button><br />
                    <video ref={videoRef} controls autoPlay playsInline></video><br />
                </div>
                <div>
                    <Button onClick={getSnap} type="primary">截取</Button><br />
                    <canvas ref={canvasRef}></canvas><br />
                </div>
            </div>
        </div>
    );
}

export default CanvasSnap;